<?php
// +----------------------------------------------------------------------
// | 商家模块
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Category as CategoryModel;
use app\user\model\Level as LevelModel;
use util\Tree;

/**
 * 分类控制器
 * @package app\mall\admin
 */
class Category extends Admin
{
    /**
     * 分类列表
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();

		// 数据列表
		$data_list = CategoryModel::where($map)->column('*', 'id');
		if (empty($map)) {
		    $data_list = Tree::toList($data_list);
		}
		$btnAdd = [
		    'class' => 'btn btn-xs btn-default',
		    'icon'  => 'fa fa-fw fa-plus',
		    'title' => '新增子分类',
		    'href'  => url('add', ['pid' => '__id__'])
		];
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['title' => '分类名称']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
               ['id', 'ID'],
			   ['icon', '图标', 'picture'],
               ['title', '分类名称', 'callback', function($value, $data){
                   return isset($data['title_prefix']) ? $data['title_display'] : $value;
               }, '__data__'],
               ['sort', '排序', 'text.edit'],
               ['status', '状态', 'switch'],
               ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable') // 批量添加顶部按钮
            ->addRightButton('edit') // 添加右侧按钮
            ->addRightButton('delete', ['data-tips' => '删除分类前，请确保分类下无商品！']) // 添加右侧按钮
			->addRightButton('custom', $btnAdd)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 新增分类
     * @param int $pid 父级id
     */
    public function add($pid = 0)
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
			
			// 分割授权店铺数据
			$data['auth'] = implode(',', $data['auth']);
			
            // 验证
            $result = $this->validate($data, 'Category');
            if(true !== $result) $this->error($result);

            if ($type = CategoryModel::create($data)) {
                cache('mall_category_list', null);
				cache('mall_category_column', null);
                // 记录行为
                action_log('category_add', 'mall_category', $type['id'], UID, $data['title']);
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }
		$category = CategoryModel::getTreeList();
        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
				['select:8', 'pid', '上级分类', '', $category, $pid],
                ['text:8', 'title', '分类名称', '<span class="text-danger">必填</span>'],
				['image:8', 'icon', '分类图标', '', '', '', '', '', '', '', '', 'local'],
				['checkbox', 'auth', '授权店铺', '', LevelModel::shop_list()],
				['radio', 'status', '立即启用', '', ['否', '是'], 1],
                ['text:8', 'sort', '排序', '', 100],
            ])
            ->fetch();
    }

    /**
     * 编辑分类
     */
    public function edit($id = '')
    {
        if ($id === 0) $this->error('参数错误');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
			
			// 分割授权店铺数据
			$data['auth'] = implode(',', $data['auth']);
			
            // 验证
            $result = $this->validate($data, 'Category');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
			
            if (CategoryModel::update($data)) {
                // 记录行为
                action_log('category_edit', 'mall_category', $id, UID, $data['title']);
				cache('mall_category_list', null);
				cache('mall_category_column', null);
				cache('mall_category_info_'. $id, null);
                return $this->success('编辑成功', 'index');
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = CategoryModel::where('id', $id)->find();
		$info['auth'] = explode(',', $info['auth']);
		$category = CategoryModel::getTreeList();
        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
				['select:8', 'pid', '上级分类', '', $category],
                ['text:8', 'title', '分类名称', '<span class="text-danger">必填</span>'],
                ['image:8', 'icon', '分类图标', '', '', '', '', '', '', '', '', 'local'],
				['checkbox', 'auth', '授权店铺', '', LevelModel::shop_list()],
                ['radio', 'status', '立即启用', '', ['否', '是']],
                ['text:8', 'sort', '排序'],
            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除分类
     * @param null $ids 分类id
     */
    public function delete($ids = null)
    {
        if ($ids === null) $this->error('参数错误');
		
		// 清除缓存
		cache('mall_category_list', null);
		cache('mall_category_column', null);
		
        // 删除并记录日志
        $column_name = CategoryModel::where('id', 'in', $ids)->column('title');
		
        return parent::delete(['category_delete', 'mall_category', 0, UID, $column_name]);
    }

    /**
     * 启用分类
     * @param array $record 行为日志
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用分类
     * @param array $record 行为日志
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置分类状态：删除、禁用、启用
     * @param string $type 分类：enable/disable
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids           = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		// 清除缓存
		cache('mall_category_list', null);
		cache('mall_category_column', null);
		
        $column_delete = is_array($ids) ? '' : $ids;
        $column_names  = CategoryModel::where('id', 'in', $ids)->column('title');
        return parent::setStatus($type, ['category_'.$type, 'mall_category', $column_delete, UID, implode('、', $column_names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $column  = CategoryModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $column . ')，新值：(' . $value . ')';
        return parent::quickEdit(['category_edit', 'mall_category', $id, UID, $details]);
    }
}